package com.yunyao.web.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.yunyao.common.dto.excel.ContractExcelDto;
import com.yunyao.common.dto.excel.SupplyExcelDto;
import com.yunyao.common.dto.supplier.ContractDto;
import com.yunyao.common.dto.PoSyupplyDto;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.framework.dto.contract.ContractWirePaySaveDto;
import com.yunyao.framework.dto.file.FileInfoDto;
import com.yunyao.framework.dto.posyupply.*;
import com.yunyao.framework.service.PoSyupplyOrderService;
import com.yunyao.framework.service.PoSyupplyService;
import com.yunyao.framework.vo.contract.ContractNodePayVO;
import com.yunyao.framework.vo.contract.ContractWirePayVO;
import com.yunyao.framework.vo.posupply.PoSyupplyMaterialVO;
import com.yunyao.framework.vo.posupply.PoSyupplyVo;
import com.yunyao.framework.vo.posupply.PoSyupplyinfoVO;
import com.yunyao.web.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/posupply")
public class PoSyupplyController {
    @Autowired
    private PoSyupplyService poSyupplyService;
    @Autowired
    private PoSyupplyOrderService poSyupplyOrderService;


    /**
     * 获取供货清单列表
     *
     * @param poSyupplyDto
     * @return
     */
    @GetMapping("/list")
    public YResult<PageResult<PoSyupplyVo>> getList(PoSyupplyDto poSyupplyDto) {
        return poSyupplyService.pageList(poSyupplyDto);
    }

    /**
     * 获取供货清单详情信息
     *
     * @param id
     * @return
     */
    @GetMapping("/info")
    public YResult<PoSyupplyinfoVO> getInfo(String id) {
        return poSyupplyService.getPoSupplyById(id);
    }


    /**
     * 保存供货清单信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/save")
    public YResult<String> saveInfo(@RequestBody PoSosyupplySaveDto saveDto) {
        return poSyupplyService.saveInfo(saveDto);
    }
    @PostMapping("/uploade")
    public YResult<String> uploade(@RequestBody PoSosyupplyUploadedDto saveDto) {
        return poSyupplyService.uploade(saveDto);
    }

    /**
     * 云采确认（供应商）
     */
    @PostMapping("/commitAudit")
    public YResult<String> auditOrder(@RequestBody PoSyupplyDto dto) {
        return poSyupplyService.audit(dto);
    }
    /**
     * 根据id删除供货清单信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/delete")
    public YResult<Boolean> deleteInfo(@RequestBody PoSosyupplySaveDto saveDto) {
        return poSyupplyService.deleteInfo(saveDto);
    }

    /**
     * 获取供货材料列表
     *
     * @param poSyupplyMaterialDto
     * @return
     */
    @GetMapping("/material/list")
    public YResult<PageResult<PoSyupplyMaterialVO>> getContractMaterialList(PoSyupplyMaterialDto poSyupplyMaterialDto) {
        return poSyupplyOrderService.getSoSupplyMaterialList(poSyupplyMaterialDto);
    }

    /**
     * 获取合同付款方式信息
     *
     * @param contractDto
     * @return
     */
    @GetMapping("/wire/pay/info")
    public YResult<ContractWirePayVO> getWirePayInfo(ContractDto contractDto) {
        return poSyupplyOrderService.getWirePayInfo(contractDto);
    }

    /**
     * 获取合同付款方式节点信息列表
     *
     * @param contractDto
     * @return
     */
    @GetMapping("/node/pay/list")
    public YResult<PageResult<ContractNodePayVO>> getContractNodePayList(ContractDto contractDto) {
        return poSyupplyOrderService.getContractNodePayList(contractDto);
    }

    /**
     * 保存合同付款方式信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/wire/pay/save")
    public YResult<String> savePayInfo(@RequestBody ContractWirePaySaveDto saveDto) {
        return poSyupplyOrderService.savePayInfo(saveDto);
    }

    /**
     * 保存合同材料信息
     *
     * @param saveDto
     * @return
     */
    @PostMapping("/material/save")
    public YResult<String> saveMaterialInfo(@RequestBody PoSyupplyMaterialSaveDto saveDto) {
        return poSyupplyOrderService.saveMaterialInfo(saveDto);
    }

    /**
     * 删除合同材料信息
     *
     * @param deletedDto
     * @return
     */
    @PostMapping("/material/deleted")
    public YResult<String> deletedMaterialInfo(@RequestBody PoSyupplyMaterialDeletedDto deletedDto) {
        return poSyupplyOrderService.deletedMaterialInfo(deletedDto);
    }

    @GetMapping("/export/file")
    public YResult<String> exportFile(PoSyupplyDto poSyupplyDto, HttpServletResponse response) {
        try {
            List<SupplyExcelDto> contractMaterialExportDtoList =  poSyupplyService.export(poSyupplyDto);
            try {
                // 这里URLEncoder.encode可以防止中文乱码
                String fileName = URLEncoder.encode("posupply", String.valueOf(StandardCharsets.UTF_8))+".xlsx";
//                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                //设置sheet名
                ExportParams params = new ExportParams();
                params.setSheetName("清单信息模版");
                //设置标题
//                params.setTitle("商品信息");
                // 这里需要设置不关闭流
                Workbook workbook = ExcelExportUtil.exportExcel(params, SupplyExcelDto.class, contractMaterialExportDtoList);
                //输出流
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                workbook.write(bos);
                byte[] bytes = bos.toByteArray();
                bos.close();
                try {
                    FileInfoDto fileInfoDto = AliOssUtil.upload(bytes,
                            fileName, null);
                    if (null != fileInfoDto) {
                        return YResult.success(fileInfoDto.getLink());
                    } else {
                        return YResult.error("连接文件服务器失败，请重试");
                    }
                } catch (Exception e) {
                    return YResult.error("下载失败，请重试");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }catch (Exception e) {
            log.error("导出清单信息失败",e);
        }
        return YResult.error("导出清单信息失败");
    }
}
